//
//  MyArtViewController.m
//  jingdongfang
//
//  Created by 郝志宇 on 16/7/11.
//  Copyright © 2016年 XuDong Jin. All rights reserved.
//

#import "MyArtViewController.h"
#import "ZuoPinCell.h"
#import "XiangQingViewController.h"
#import "FindLayout.h"
#import "OpenZuopinCell.h"
#import "IGGetUploadApi.h"
#import "IGdeletWorksApi.h"
#import "IGiGalleryListApi.h"
#import "IGiGalleryPushApi.h"
#import "IGPushiGalleryListVC.h"
#import "SiMiViewController.h"
#import "IGPreIssueView.h"
#import "UpPrintVC.h"
#import "PhotoUpLoadAgreementViewController.h"
#import "UserUNidentyViewController.h"
#import "BatchUploadVC.h"

@interface MyArtViewController () <UICollectionViewDataSource, UICollectionViewDelegateFlowLayout> {
    UICollectionView *collect;
    UIButton *upBtn;
    
    NSMutableArray *selArr;
    UIView *tabbar;
    UIView *nonView;
    
    NSString *p_idsStr;
    NSString *uId;
    NSString *secrecy;//1公开, 2保密
    NSInteger pageNumber;//页数，从0开始
    NSString *queryTime;//查询时间
    IGArtWorkModel *info ;
    SiMiViewController *v2;
    NSString *pushSuccess;
    
}
@property (nonatomic, strong)IGGetUploadApi *uploadApi;
@property (nonatomic, strong)NSMutableArray *uploadDataArr;
@property (nonatomic, strong)IGdeletWorksApi *deletApi;
@property (nonatomic, strong) IGiGalleryListApi *igalleryListApi;
@property (nonatomic, strong) NSArray *iGalleryListArr;
@property (nonatomic, strong) IGPreIssueView *issueView;

@end

@implementation MyArtViewController

#pragma mark - 懒加载
-(NSMutableArray *)uploadDataArr{
    if (!_uploadDataArr) {
        _uploadDataArr=[NSMutableArray array];
    }
    return _uploadDataArr;
}
#pragma mark - 生命周期
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor =[UIColor c2Color];
    upBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    upBtn.frame=CGRectMake(15, 15, KSCREENWIDTH-30, 40);
    upBtn.clipsToBounds=YES;
    upBtn.layer.borderWidth=1.0f;
    upBtn.layer.cornerRadius=5.f;
    upBtn.layer.borderColor=[UIColor c1Color].CGColor;
    upBtn.titleLabel.font=[UIFont font14];
//    [upBtn setTitle:@"上传公开作品" forState:UIControlStateNormal];
    [upBtn setTitle:NSLocalizedString(@"Upload Public Works", nil) forState:UIControlStateNormal];
    [upBtn setTitleColor:[UIColor c1Color] forState:UIControlStateNormal];
    upBtn.userInteractionEnabled=YES;
    [upBtn addTarget:self action:@selector(upPhoto) forControlEvents:UIControlEventTouchUpInside];
    
    FindLayout *layout = [[FindLayout alloc] init];
    collect = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, KSCREENHEIGHT-NavigationMagin-44-20) collectionViewLayout:layout];
    collect.backgroundColor = [UIColor clearColor];
    collect.delegate = self;
    collect.dataSource = self;
    if (@available(iOS 11.0, *)) {
        collect.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        collect.contentInset = UIEdgeInsetsMake(0, 0, 49, 0);
        collect.scrollIndicatorInsets = collect.contentInset;
    }
    collect.alwaysBounceVertical = YES;
    [collect registerClass:[OpenZuopinCell class] forCellWithReuseIdentifier:@"myArtCell"];
    nonView=[[UIView alloc]initWithFrame:CGRectMake(0, 60, KSCREENWIDTH, 100)];
    nonView.backgroundColor=[UIColor clearColor];
    UILabel *nonLable=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, 60)];
    nonLable.center=nonView.center;
//    nonLable.text=@"您还没有上传任何公开作品\n快去上传吧~";
    nonLable.text=NSLocalizedString(@"Nothing uploaded yet. Go Upload Now.", nil);
    nonLable.numberOfLines=2;
    nonLable.textAlignment=NSTextAlignmentCenter;
    nonLable.font=[UIFont font16];
    nonLable.textColor=[UIColor blackColor];
    [nonView addSubview:nonLable];
    nonView.hidden=YES;
    collect.top=upBtn.bottom+10;
    [collect addSubview:nonView];
    
    UILongPressGestureRecognizer *longTap = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longTap:)];
    [collect addGestureRecognizer:longTap];
    [self.view addSubview:upBtn];
    [self.view addSubview:collect];
     [self setIsEdit:NO];
    self.uploadApi = [IGGetUploadApi new];
    [self firstPage];
    [self requestIGlist];
    @KWeakObj(self)
    [collect ig_setHeaderWithRefreshingBlock:^{
        [selfWeak firstPage];
    }];
}
- (void)firstPage
{
    secrecy = @"1";
    pageNumber = 0;
    queryTime = @"";
    [self requestData];
}

- (void)scrollToTOP
{
    if ([pushSuccess isEqualToString:@"1"]) {
        if (self.isEdit) {
            [self canel];
            self.editBlock(NO);
        }
        pushSuccess=@"0";
    }
    
    [collect setContentOffset:CGPointMake(0, 0) animated:YES];
}

-(void)requestData
{
    @KWeakObj(self)
    selfWeak.uploadApi.secrecy=secrecy;
    selfWeak.uploadApi.pageNumber=pageNumber;
    selfWeak.uploadApi.queryTime = queryTime;
    [self.uploadApi startWithDecodeClass:[IGGetUploadResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        [collect ig_endHeaderRefreshing];
        [collect ig_endFooterRefreshing];
        if (responseObject)
        {
            IGGetUploadResp *resp = responseObject;
            IGGetUploadModel *model = resp.data;
            if (model.lstWork && model.lstWork.count > 0)
            {
                [selfWeak setupFooter];
            }
            queryTime = model.queryTime;
            if (pageNumber == 0)
            {
                _uploadDataArr = [NSMutableArray arrayWithArray:model.lstWork];
                if (_uploadDataArr.count==0) {
                    nonView.hidden=NO;
                    tabbar.hidden=YES;
                    [collect ig_removeFooterRefreshing];
                }
            }
            else
            {
                if (model.lstWork.count==0) {
                    [collect ig_endFooterRefreshingWithNoMoreData];
                }
                [_uploadDataArr addObjectsFromArray:model.lstWork];
                for (int i=0; i<model.lstWork.count; i++) {
                    [selArr addObject:@(NO)];
                }
            }
            [collect reloadData];
        }
        else
        {
        }
    }];
    
}
- (void)setupFooter
{
    @KWeakObj(self)
    [collect ig_setFooterWithRefreshingBlock:^{
        pageNumber++;
//        if (selfWeak.isEdit) {
//            [self canel];
//        }
//        self.editBlock(NO);
        [selfWeak requestData];
    }];
}

#pragma mark - UICollectionViewDataSource, UICollectionViewDelegateFlowLayout

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _uploadDataArr.count?_uploadDataArr.count:0;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    OpenZuopinCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"myArtCell" forIndexPath:indexPath];
    cell.data = _uploadDataArr[indexPath.item];
    cell.isEdit = self.isEdit;
    if (self.isEdit) {
        cell.isSel = [selArr[indexPath.item] boolValue];
    }
    [cell setNeedsLayout];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (self.isEdit) {
        
        NSMutableArray *selIndexArr = [NSMutableArray array];
        for (int i=0; i<selArr.count; i++) {
            NSNumber *s = selArr[i];
            if ([s boolValue]) {
                [selIndexArr addObject:@(i)];
            }
        }
        
        if (selIndexArr.count >= 8) {
            
            BOOL canel = NO;
            for (NSNumber *index in selIndexArr) {
                if (indexPath.item==[index integerValue]) {
                    canel = YES;
                    break;
                }
            }
            
            if (!canel) {
//                [self presentMessageTips:@"最多可选8张"];
                [self presentMessageTips:NSLocalizedString(@"Select no more than 8 pictures", nil)];
                return;
            }
        }
        
        BOOL sel = [selArr[indexPath.item] boolValue];
        [selArr removeObjectAtIndex:indexPath.item];
        [selArr insertObject:@(!sel) atIndex:indexPath.item];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [collect reloadData];
        });
//        [collectionView reloadData];
        
    }else{
        IGArtWorkModel *list = _uploadDataArr[indexPath.item];
        XiangQingViewController *vc = [[XiangQingViewController alloc] init];
        vc.p_id = list.aId;
        vc.isRoot = YES;
        [UIViewController ig_pushViewController:vc animated:YES];
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    IGArtWorkModel *f = _uploadDataArr[indexPath.item];
    if ([f.plates integerValue]==1)
    {
        //横板
        return CGSizeMake((KSCREENWIDTH-16)/2, ((KSCREENWIDTH-16)/2*1080/1920));
    }
    else if ([f.plates integerValue]==2)
    {
        //坚板
        return CGSizeMake((KSCREENWIDTH-16)/2, ((KSCREENWIDTH-16)/2*1920/1080));
    }
    return CGSizeMake(0, 0);
    
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(5, 5, 5, 5);
}
#pragma mark -长按
- (void)longTap:(UIGestureRecognizer *)longTap {
    if (!self.isEdit) {
        self.isEdit = YES;
        
        selArr = [NSMutableArray array];
        for (int i=0; i<_uploadDataArr.count; i++) {
            [selArr addObject:@(NO)];
        }
        
        if (self.editBlock) {
            self.editBlock(YES);
        }
        
        if (!tabbar) {
            tabbar = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, 49)];
            tabbar.backgroundColor = [UIColor whiteColor];
            [self.view addSubview:tabbar];
            
            UIButton *del = [UIButton buttonWithType:UIButtonTypeCustom];
            del.titleLabel.font = [UIFont systemFontOfSize:15];
            [del setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//            [del setTitle:@"删除" forState:UIControlStateNormal];
            [del setTitle:NSLocalizedString(@"Delete", nil) forState:UIControlStateNormal];
            [del setImage:[UIImage imageNamed:@"C-13-3"] forState:UIControlStateNormal];
            [del addTarget:self action:@selector(delModel:) forControlEvents:UIControlEventTouchUpInside];
            [del setImageEdgeInsets:UIEdgeInsetsMake(0, -5, 0, 5)];
             del.frame = CGRectMake(0, 0, KSCREENWIDTH/3, 49);
            [tabbar addSubview:del];
            
            UIButton *push = [UIButton buttonWithType:UIButtonTypeCustom];
            push.backgroundColor = [UIColor appColor];
            push.titleLabel.font = [UIFont systemFontOfSize:15];
            [push setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//            [push setTitle:@"推送到画屏" forState:UIControlStateNormal];
            [push setTitle:NSLocalizedString(@"Push to iGallery", nil) forState:UIControlStateNormal];
            [push addTarget:self action:@selector(pushPhoto:) forControlEvents:UIControlEventTouchUpInside];
            push.frame = CGRectMake(del.right, 0, KSCREENWIDTH/3*2, 49);
            [tabbar addSubview:push];
            
            UILabel *line = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, .5)];
            line.backgroundColor = [UIColor lightGrayColor];
            [tabbar addSubview:line];
        }
        tabbar.top = self.view.height;
        [UIView animateWithDuration:.3 animations:^{
            if ([UIApplication sharedApplication].statusBarFrame.size.height!=20) {
                tabbar.bottom=self.view.height-20;
            }else{
            tabbar.bottom = self.view.height;
            }
        } completion:^(BOOL finished) {
            collect.mj_header.hidden = YES;
            collect.contentInset = UIEdgeInsetsMake(0, 0, 49*2, 0);
            [collect reloadData];
        }];
    }
}
#pragma mark - 删除作品
- (void)delModel:(UIButton *)btn
{
    @KWeakObj(self)
    NSMutableArray *selIndexArr = [NSMutableArray array];
    for (int i=0; i<selArr.count; i++) {
        NSNumber *s = selArr[i];
        if ([s boolValue]) {
            [selIndexArr addObject:@(i)];
        }
    }
    if (selIndexArr.count==0) {
//        [self presentMessageTips:@"至少选择一个作品"];
        [self presentMessageTips:NSLocalizedString(@"Select at least one Work", nil)];
        return;
    }
    
    NSMutableArray *infoArr = [NSMutableArray array];
    for (NSNumber *index in selIndexArr) {
        info = _uploadDataArr[[index integerValue]];
        [infoArr addObject:info.aId];
    }
    p_idsStr = [infoArr componentsJoinedByString:@","];
    [UIAlertView bk_showAlertViewWithTitle:NSLocalizedString(@"Notice", nil) message:NSLocalizedString(@"Confirm to delete this picture/these pictures?",nil) cancelButtonTitle:NSLocalizedString(@"Cancel", nil) otherButtonTitles:@[NSLocalizedString(@"Confirm", nil)] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
        if (buttonIndex == 1) {
            self.deletApi = [IGdeletWorksApi new];
            self.deletApi.worksIds=p_idsStr;
            [self.deletApi startWithDecodeClass:[IGdeletWorksResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
                if (responseObject)
                {
                    [selfWeak canel];
                    [selfWeak firstPage];
                    self.editBlock(NO);
                }
            }];
        }
    }];
    
}

#pragma mark -推送作品
- (void)pushPhoto:(UIButton *)btn
{
    NSMutableArray *selIndexArr = [NSMutableArray array];
    for (int i=0; i<selArr.count; i++) {
        NSNumber *s = selArr[i];
        if ([s boolValue]) {
            [selIndexArr addObject:@(i)];
        }
    }
    
    if (selIndexArr.count==0) {
//        [self presentMessageTips:@"至少选择一个作品"];
        [self presentMessageTips:NSLocalizedString(@"Select at least one Work", nil)];
        return;
    }
    
    NSMutableArray *infoArr = [NSMutableArray array];
    for (NSNumber *index in selIndexArr) {
        IGArtWorkModel *work = _uploadDataArr[[index integerValue]];
        [infoArr addObject:work];
    }
    
    if (self.iGalleryListArr.count == 0) {
//        [self presentMessageTips:@"当前无绑定设备"];
        [self presentMessageTips:NSLocalizedString(@"No linked device found", nil)];
    } else if (self.iGalleryListArr.count == 1) {
        [self pushToDev:infoArr];
    } else {
        IGPushiGalleryListVC *listVC = [[IGPushiGalleryListVC alloc] initWithType:IGPushiGalleryTypeNN];
        listVC.recommendArr = infoArr;
        listVC.successBlock = ^(NSString *strValue) {
            pushSuccess=strValue;
        };
        [UIViewController ig_pushViewController:listVC animated:YES];
    }
}

- (void)pushToDev:(NSArray *)infoArr
{
    NSMutableArray *aIds = [NSMutableArray array];
    for (IGArtWorkModel *info in infoArr) {
        [aIds addObject:info.aId];
    }
    IGiGalleryEqu *equ = self.iGalleryListArr[0];
    IGiGalleryPushApi *pushApi = [[IGiGalleryPushApi alloc] initWithMacIds:@[equ.macId] pIds:aIds];
    //    [self presentMessageTips:@"正在推送..."];
    [self presentMessageTips:NSLocalizedString(@"Pushing...", nil)];
    [pushApi startWithDecodeClass:[IGiGalleryPushResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject) {
            //            [self presentMessageTips:@"推送成功..."];
            [self presentMessageTips:NSLocalizedString(@"Pushed Successfully...\n Would show up until device online.", nil)];
            [self firstPage];
            [self canel];
            self.editBlock(NO);
        }
    }];
}

#pragma mark -请求设备列表
-(void)requestIGlist{
    self.igalleryListApi = [[IGiGalleryListApi alloc] initWithType:IGiGalleryListTypeSuccess];
    __weak typeof(self) weakSelf = self;
    [self.igalleryListApi startWithDecodeClass:[IGiGalleryListResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject) {
            IGiGalleryListResp *resp = responseObject;
            IGiGalleryListModel *model = resp.data;
            weakSelf.iGalleryListArr = [NSArray arrayWithArray:model.equs];
        }
    }];
    
}

- (void)canel
{
    if (self.isEdit)
    {
        self.isEdit=NO;
        [UIView animateWithDuration:.2 animations:^{
            tabbar.top = self.view.height;
        } completion:^(BOOL finished) {
            collect.contentInset = UIEdgeInsetsMake(0, 0, 49, 0);
            collect.mj_header.hidden = NO;
            [collect reloadData];
        }];
    }
    else if(self.isEdit==NO)
    {
        self.isEdit=YES;
        selArr = [NSMutableArray array];
        for (int i=0; i<_uploadDataArr.count; i++)
        {
            [selArr addObject:@(NO)];
        }
        
        if (!tabbar)
        {
            tabbar = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, 49)];
            tabbar.backgroundColor = [UIColor whiteColor];
            [self.view addSubview:tabbar];
            
            UIButton *del = [UIButton buttonWithType:UIButtonTypeCustom];
            del.titleLabel.font = [UIFont systemFontOfSize:15];
            [del setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//            [del setTitle:@"删除" forState:UIControlStateNormal];
            [del setTitle:NSLocalizedString(@"Delete", nil) forState:UIControlStateNormal];
            [del setImage:[UIImage imageNamed:@"C-13-3"] forState:UIControlStateNormal];
            [del addTarget:self action:@selector(delModel:) forControlEvents:UIControlEventTouchUpInside];
            [del setImageEdgeInsets:UIEdgeInsetsMake(0, -5, 0, 5)];
            del.frame = CGRectMake(0, 0, KSCREENWIDTH/3, 49);
            [tabbar addSubview:del];
            
            UIButton *push = [UIButton buttonWithType:UIButtonTypeCustom];
            push.backgroundColor =[UIColor appColor];
            push.titleLabel.font = [UIFont systemFontOfSize:15];
            [push setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//            [push setTitle:@"推送到画屏" forState:UIControlStateNormal];
            [push setTitle:NSLocalizedString(@"Push to iGallery", nil) forState:UIControlStateNormal];
            [push addTarget:self action:@selector(pushPhoto:) forControlEvents:UIControlEventTouchUpInside];
            push.frame = CGRectMake(del.right, 0, KSCREENWIDTH/3*2, 49);
            [tabbar addSubview:push];
            
            UILabel *line = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, .5)];
            line.backgroundColor = [UIColor lightGrayColor];
            [tabbar addSubview:line];
        }
        tabbar.top = self.view.height;
        [UIView animateWithDuration:.2 animations:^{
            tabbar.bottom = self.view.height;
        } completion:^(BOOL finished) {
            collect.mj_header.hidden = YES;
            collect.contentInset = UIEdgeInsetsMake(0, 0, 49, 0);
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [collect reloadData];
            });
        }];
    }
}

#pragma mark -点击上传公开作品
-(void)upPhoto{
    @KWeakObj(self)
    /** 发布公开图片 */
    //1 未认证, 2 已认证,3 待认证,4 认证未通过
    if ([[IGUser getAuthens] isEqualToString:@"3"])
    {//待认证
//        [selfWeak presentMessageTips:@"身份认证审核中"];
        [selfWeak presentMessageTips:NSLocalizedString(@"ID under Verification", nil)];
    }
    else if([[IGUser getAuthens] isEqualToString:@"2"])
    {//通过
        [IGPermissionUtil ig_showActionSheetWithCameraBlock:^{
            [IGTakePhotosUtil ig_showImagePickerControllerWithImagePickerBlock:^(NSDictionary<NSString *,id> * _Nullable info)
             {
                 UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
                 image = [image fixOrientation];
                 UpPrintVC *vc = [[UpPrintVC alloc] initWithImage:image];
                 vc.isOpen = YES;
                 [UIViewController ig_pushViewController:vc animated:YES];
             }];
        } photoBlock:^{
            [IGTakePhotosUtil ig_showAssetsForProductPickerControllerWithMaximumNumberOfSelection:1 assetsPickerBlock:^(NSArray<UIImage *> * _Nullable photos, NSArray * _Nullable assets) {
                //选择一张时进入裁剪界面
                dispatch_async(dispatch_get_main_queue(), ^{
                    //选择一张时进入裁剪界面
                    if (photos.count == 1)
                    {
                        UIImage *image = photos[0];
                        UpPrintVC *vc = [[UpPrintVC alloc] initWithImage:image];
                        vc.assets = assets;
                        vc.isOpen = YES;
                        [UIViewController ig_pushViewController:vc animated:YES];
                    }
//                    //选则多张时进入批量上传界面
//                    else if (photos.count > 1)
//                    {
//                        BatchUploadVC *vc = [[BatchUploadVC alloc] init];
//                        vc.assets = [NSMutableArray arrayWithArray:assets];
//                        vc.images = [NSMutableArray arrayWithArray:photos];
//                        [UIViewController ig_pushViewController:vc animated:YES];
//                    }
                });
            }];
        }];
    }
    else
    {
        if ([[IGUser getAuthens] isEqualToString:@"1"] || ![IGUser getAuthens])
        {//未认证
            PhotoUpLoadAgreementViewController *photoAgreenmentVC = [[UIStoryboard storyboardWithName:@"UserCertification" bundle:nil] instantiateViewControllerWithIdentifier:@"PhotoUpLoadAgreementViewController"];
            [UIViewController ig_pushViewController:photoAgreenmentVC animated:YES];
        }
        else if([[IGUser getAuthens] isEqualToString:@"4"])
        {//不通过
            UserUNidentyViewController *vc=[[UserUNidentyViewController alloc]initWithNibName:@"UserUNidentyViewController" bundle:nil];
            [UIViewController ig_pushViewController:vc animated:YES];
        }
    }
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}


@end
